<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Request;
use think\Db;
use think\Log;

use app\common\library\ApiToken;

/**
 * 首页接口
 */
class Index extends Api
{
	
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

	protected $tokenExpireMinute = 300; // token 失效时间 单位:秒
	
	public function __construct(){
		parent::__construct();
	}
	
    /**
     * 首页
     * 
     */
    public function index()
    {	
		$apiSn = 'SN1000';
		
		$r1 = $this->doParameterCheck($apiSn);
		
		_print($r1);exit;
	
        $this->success('请求成功');
    }
	
	// 根据接口序号，获得接口的配置信息
	public function getApiSetting( $apiSn = null, $field = '*' )
	{
		if(empty($apiSn)){
			return [];
		}
		
		$apiConf = Db::name("apiconfig")->where(['apisn' => $apiSn])->field($field)->find();
		
		return $apiConf;		
	}
	
	// 记录接口调用的次数
	public function setDayCallingTimes($apiSn = null, $instrument_sn = null)
	{
		if(empty($apiSn) || empty($instrument_sn)){
			$this->error(__('Missing Parameter'));
		}
		
		$where = [
			'apisn' => $apiSn,
			'instrument_sn' => $instrument_sn,
			'apiday' => date('Y-m-d')
		];
		
		$row = Db::name('apidaycalling')->where($where)->find();
		
		if(empty($row)){
			$where['createtime'] = $where['updatetime'] = time();
			$res = Db::name('apidaycalling')->insert($where);
			if($res) {
				return true;
			}
			return false;
		} else {
			$data = [
				'apitimes' => $row['apitimes'] + 1 ,
				'updatetime' => time()
			];
			$where = [
				'id' => $row['id']
			];
			
			$res = Db::name('apidaycalling')->where($where)->update($data);
			if($res) {
				return true;
			} 
			return false;
		}

	}
	

	// 获得获取令牌 token
	public function token($apiSn = 'SN1000')
	{	
		// 检验重要参数 及合法性
		$instrument_sn = $this->request->get('instrument_sn') ?: '';		
		if(empty($instrument_sn)) {
			$this->error(__('Missing Parameter'));
		}
		// 检查仪器序列号的合法性
		$this->doCheckInstrumentSn($instrument_sn);
		
		
		// 检查参数的有效性
		$this->doParameterCheck($apiSn);		
		$apiResponse = $this->apiResponse[$apiSn];
		
		if(!$apiResponse['code']){			
			$this->error(__('Invalid Argument'));
			$this->doApiLog($apiSn, $instrument_sn, $apiResponse['code'], __('Invalid Argument'));
		}

		// 检查接口调用次数
		$this->doTimesCheck($apiSn, $instrument_sn);
		
		
		$tokenData = ApiToken::is_token($instrument_sn);		
		$token = null;
		if(empty($tokenData)){
			$token = ApiToken::token();
			ApiToken::set($token, $instrument_sn, $this->tokenExpireMinute);	
			// 成功调用一次，记录
			$this->setDayCallingTimes($apiSn, $instrument_sn); 	
			$this->doApiLog($apiSn, $instrument_sn, '1', __('Get Token').':token='.$token);				
		}
		else {
			$token = $tokenData->getData()['token'];
		}			
			
		$this->success(__('Get Token') ,['token' => $token]);		
	}
	
	// 上传文件信息
	public function upload_info($apiSn = 'SN1004')
	{	
		// 检验重要参数 及合法性
		$instrument_sn = $this->request->get('instrument_sn') ?: '';		
		if(empty($instrument_sn)) {
			$this->error(__('Missing Parameter'));
		}
		
		// 检查参数的有效性
		$this->doParameterCheck($apiSn);		
		$apiResponse = $this->apiResponse[$apiSn];	
		
		if(!$apiResponse['code']){			
			$this->error(__('Invalid Argument'), $apiResponse);
			$this->doApiLog($apiSn, $instrument_sn, $apiResponse['code'], __('Invalid Argument'));
		} 
		
		// 检查接口调用次数
		$this->doTimesCheck($apiSn, $instrument_sn);
		
		// 接受数据
		$data = array();
		// 必填数据
		$dataRequireFields = ['project_name','file_name','file_length','package_num'];
		foreach($dataRequireFields as $v){
			$data["$v"] = $this->request->get($v, '');			
			if(empty($data["$v"])){
				$this->error(__('Missing Require Parameter').','.$v);
			}
		}
		// 可选数据
		$dataOptionFields = ['field1','field2','field3','field4','field5'];
		foreach($dataOptionFields as $v){
			$data["$v"] = $this->request->get($v, '');
		}
		// 其他数据 - 冗余
		// 获得仪器序列号销售情况
		$r = $this->getAdminIdByInstrumentSn($instrument_sn, "admin_id, instumenttype, instumentname");		
		$admin_id = 1;
		$instrumenttype = 'no type';
		if(count($r)){
			$admin_id = $r['admin_id'];
			$instrumenttype = $r['instumenttype'];
			$instumentname = $r['instumentname'];
		}
		$data['instrumentsno'] = $instrument_sn;
		$data['instrumenttype'] = $instrumenttype;
		$data['instrumentname'] = $instumentname;
		$data['admin_id'] = $admin_id;
		$data['createtime'] = time();
		
		// 上传文件信息的数据唯一性检索
		$unique_key = [
			'instrumentsno' => $instrument_sn,
			'project_name' => $data["project_name"],
			'file_name' => $data['file_name']
		];
		
/* 		_print($unique_key);
		_print($data); */
		// 先查看是否存在
		$r = Db::name('apifile')->where($unique_key)->field('id')->find();
		
		// 上传文件存放数据的仓库编码
		$insertId = 0;
		if(is_null($r)){			
			$insertResult = Db::name('apifile')->insert($data);
			if($insertResult) {
				$insertId = Db::name('apifile')->getLastInsID();
				// 记录API调用日志
				$this->doApiLog($apiSn, $instrument_sn, '1', __('Get StorageSn').':file_cloud_name='.$insertId);	
			}			
		
		} else {
			$insertId = $r['id'] ? $r['id'] : 0;
		}
		
		// 成功调用一次，记录
		$this->setDayCallingTimes($apiSn, $instrument_sn); 	
				
		if($insertId) {
			$this->success("Sucess" ,['file_cloud_name' => $insertId]);
		} else {
			$this->error("Failure",['file_cloud_name' => null]);
		}
		
	}
	
	// 上传文件数据
	public function upload_data($apiSn = 'SN1005')
	{
		
	}
	
	// 接受仪器数据
	public function post()
	{
		$originalPostData = Request::instance()->post(false);
		$filterPostData = Request::instance()->post();
		
		//Log::record('[api/Index/post] begin ','info');
		
		if(empty($originalPostData) || empty($filterPostData)) {
			$this->error('no post data', $originalPostData);
		}

		
		$data = array();
		$memo = 'The Original POST Data is:'.var_export($originalPostData, true);
		//$memo = $memo.'; 获取经过过滤的全部post变量：'.var_export($filterPostData, true);
		$memo = mb_convert_encoding($memo, 'utf-8', 'GBK');
		$data['memo'] = $memo;
		
		//Log::record('[api/Index/post] $originalPostData => '.var_export($originalPostData, true),'info');
		

		$data['instrumentname'] = input('post.instrumentname','');
		$data['instrumentname'] = mb_convert_encoding($data['instrumentname'], 'utf-8', 'GBK');

		
		
		$data['instrumenttype'] = input('post.instrumenttype','no type');
		$data['instrumentsno'] = input('post.instrumentsno','');
		$data['projectname'] = input('post.projectname','');
		$data['data'] = input('post.data','');
			
		
		$data['createtime'] = input('post.createtime',time());
		
		if( empty($data['instrumentname']) ) {
			$this->error('the name of instrument is empty');
		}

		if( empty($data['instrumentsno']) ) {
			$this->error('the sno of instrument is empty');
		}
		
		if( empty($data['projectname']) ) {
			$this->error('the project name is empty');
		}
		
		if( empty($data['data']) ) {
			$this->error('the data is empty');
		}
		
		if(empty($data)) {
			$this->error('no data');
		}


		
		Db::name('apidata')->insert($data);
		
		
		$this->success('success');
		
		
	}
	
	
	public function getData() {
		$id = input('get.id',0);
		
		$r = Db::name('apidata')->field('data')->where(['id' => $id])->find();
		
		if($r){
			settype($r['data'],'string');
			
			exit($r['data']);	
		} else {
			$this->error('fail, no data');
		}
		
	}	
}
